package proxynew;

import java.util.Enumeration;

import net.jxta.discovery.DiscoveryEvent;
import net.jxta.discovery.DiscoveryService;
import net.jxta.document.Advertisement;
import net.jxta.platform.NetworkManager;
import net.jxta.protocol.DiscoveryResponseMsg;
import net.jxta.protocol.PipeAdvertisement;

public class DiscoveryListener extends Thread implements
		net.jxta.discovery.DiscoveryListener {
	private NetworkManager networkManager;

	public DiscoveryListener(NetworkManager networkManager) {
		this.networkManager = networkManager;
	}

	public void run() {
		DiscoveryService discovery = networkManager.getNetPeerGroup().getDiscoveryService();
        long waittime = 60 * 1000L;

        // adiciona como listener de eventos
		// events
        discovery.addDiscoveryListener(this);
        discovery.getRemoteAdvertisements(
                // no specific peer (propagate)
                null,
                //Adv type
                DiscoveryService.ADV,
                //Attribute = any
                null,
                //Value = any
                null,
                // one advertisement response is all we are looking for
                1,
                // no query specific listener. we are using a global listener
                null);

        while(true) {
        	try {
                // wait a bit before sending a discovery message
                try {
                    System.out.println("DiscoveryListener: Dormindo por :" + waittime + " ms");
                    Thread.sleep(waittime);
                } catch (Exception e) {
                    // ignored
                }
        		
        		// look for any peer
        		System.out.println("DiscoveryListener: Enviando mensagem para procurar peers.");
                discovery.getRemoteAdvertisements(
                         // no specific peer (propagate)
                         null,
                         // Adv type
                         DiscoveryService.ADV,
                         // Attribute = name
                         "Name",
                         // Value = the tutorial
                         PipeMsgListener.PIPE_NAME,
                         // one advertisement response is all we are looking for
                         11,
                         // no query specific listener. we are using a global listener
                         null);
        	 } catch (Exception e) {
				System.err.println(e.getMessage());
				e.printStackTrace();
        	 }
         } 
	}

	@Override
	public void discoveryEvent(DiscoveryEvent event) {
		DiscoveryResponseMsg res = event.getResponse();
        // let's get the responding peer's advertisement
        System.out.println("DiscoveryListener: Resposta recebida " + res.getResponseCount() 
        		+ " elementos de  : " + event.getSource() + " ]");
        Enumeration<Advertisement> en = res.getAdvertisements();
        if (en != null) {
            while (en.hasMoreElements()) {
                Advertisement adv = (Advertisement) en.nextElement();
                if (!PipeMsgListener.getPideID().toString().equalsIgnoreCase(adv.getID().toString())) {
	                if (adv instanceof PipeAdvertisement) {
	                	Pipes.getInstance().addPipe(adv.getID().toString(), (PipeAdvertisement)adv);
	                	System.out.println("DiscoveryListener: Pipe adicionado. Pipes encontrados até agora:\n" + Pipes.getInstance());;
	                }
                }
            }
        }
	}

}
